import {
	onLoad,
	onShow,
	onPullDownRefresh,
	onReachBottom
} from "@dcloudio/uni-app";
import {
	reactive
} from 'vue';
import api from '@/api/index.js'

export function usePages({
	getData
}) {
	const pagesParams = reactive({
		current: 1,
		size: 10,
		loaded: false
	})

	onPullDownRefresh(() => {
		console.log("下拉刷新")
	})

	onReachBottom(async () => {
		console.log("上拉加载更多")
		if (pagesParams.loaded) {
			return false
		}
		getData()
	})

	return {
		pagesParams
	}
}

export function uploadFile(filePath) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: api.upload, //后台地址
			filePath: filePath,
			name: "file",
			header: {
				"Content-Type": "multipart/form-data",
				"authorization": uni.getStorageSync('token')
			},
			success: (res) => {
				let result = JSON.parse(res.data)
				if (result) {
					resolve(api.imgHost + result.data)
				} else {
					reject(false)
					uni.showToast({
						icon: "none",
						title: "上传失败",
					});
				}
			},
			fail: (e) => {
				uni.showToast({
					icon: "none",
					title: "上传失败",
				});
				reject(false)
			},
		});
	})
}

export function setFileObj(url) {
	// 使用正则表达式提取文件名（不包含扩展名）
	const getName = (url) => {
		const match = url.match(/[^\/\\]+(?=\.\w+ $ )/);
		return match ? match : '';
	};

	// 使用正则表达式提取文件扩展名
	const getExtname = (url) => {
		const match = url.match(/\.\w+ $ /);
		return match ? match : '';
	};
	return {
		name: getName(url),
		extname: getExtname(url),
		url: url,
	}
}

export function preview(urls, index) {
	uni.previewImage({
		urls: urls, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
		current: urls[index], // 当前显示图片的http链接，默认是第一个
		success: function(res) {
			uni.setStorageSync('ispreviewImage', true)
		},
		fail: function(res) {},
		complete: function(res) {},
	})
}